package com.alex.core.logUtils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 访问日志工具类
 * @author cb
 * @date 2019/10/25 13:58
 */
@Component
@Slf4j
public class ActionLogUtil {

    public static final String ACTION_LOG_QUEUE = "action-log-queue";
    public static final String ACTION_LOG_EXCHANGE = "action-log";
    public static final String ACTION_LOG_KEY = "log";

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 记录访问日志
     * @param operatorId 操作人ID
     * @param operatorType 操作人类型
     *                      @see com.ddcx.contants.enums.AccountTypeEnum
     * @param loginName  登录名
     * @param roleId 角色ID
     * @param sourceName 资源名称
     * @param ip ip地址
     * @param url 访问url
     * @param tenantId 商户ID
     */
    public void recordLog(Integer operatorId, Integer operatorType, String loginName, Integer roleId, String sourceName, String ip, String url, Integer tenantId) {
        ActionLog actionLog = new ActionLog();
        actionLog.setOperatorId(operatorId);
        actionLog.setOperatorType(operatorType);
        actionLog.setLoginName(loginName);
        actionLog.setRoleId(roleId);
        actionLog.setSourceName(sourceName);
        actionLog.setIp(ip);
        actionLog.setUrl(url);
        actionLog.setTenantId(tenantId);
        actionLog.setCreateTime(new Date());
        try {
            rabbitTemplate.convertAndSend(ACTION_LOG_EXCHANGE, ACTION_LOG_KEY, JSONObject.toJSONString(actionLog));
        } catch (Exception e) {
            log.error("发送访问日志到消息队列出错，日记将会记录到模块文件日志中", e);
            log.info("记录访问日志=========>{}", JSONObject.toJSONString(actionLog));
        }
    }

}
